package com.ys.day28.socket通信方式;


import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 描述: TODO
 *
 * @author CodeYang
 * @version 2021/1/8 20:51
 */
public class MyServer1 {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket accept = serverSocket.accept();
        System.out.println("建立连接......");

        InputStream inputStream = accept.getInputStream();

        byte[] bs = new byte[1024];
        int len = 0;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while ((len = inputStream.read(bs)) != -1) {
            byteArrayOutputStream.write(bs, 0, len);
            if(bs[len-1]==-1){
                break ;
            }
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        String msg = new String(bytes);
        System.out.println(msg);


        OutputStream outputStream = accept.getOutputStream();

        outputStream.write("hello.socket".getBytes());


        outputStream.flush();

        closeRes(outputStream,inputStream,accept) ;
    }

    public static void closeRes(Closeable... res) {
        for (Closeable re : res) {
            if (re != null) {
                try {
                    re.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    re = null;
                }
            }
        }
    }
}
